# -*- encoding: utf-8 -*-
##############################################################################
#
##############################################################################

from odoo import api, fields, models, _
from odoo.addons import decimal_precision as dp
from odoo.exceptions import UserError, ValidationError
from odoo.tools import float_round

class MrpProduction(models.Model):
    """ Manufacturing Orders """
    _inherit = 'mrp.production'

    @api.multi
    def post_inventory(self):
        quantity=0
        for quantity_move in self.move_finished_ids:
            if quantity_move.product_id==self.product_id and quantity_move.state in ('confirmed','assigned'):
                quantity=quantity_move.quantity_done
        if self.picking_type_id.outsource_type and quantity>0:
            if self.procurement_id:
                if not self.procurement_id.purchase_line_id:
                    raise ValidationError(u'委外服务没有生成采购单!不允许完成生产')
                if not self.procurement_id.purchase_line_id.order_id.state <> 'done':
                    raise ValidationError(u'没有生成采购单!不允许完成生产')
                self.procurement_id.purchase_line_id.qty_received += quantity
            else:
                raise ValidationError(u'委外类型的生产单,没有服务需求,不允许完成生产')
        return super(MrpProduction, self).post_inventory()
